<template>
  <div class="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 py-8 px-4 sm:px-6 lg:px-8">
    <!-- 卡片容器 -->
    <div class="max-w-3xl mx-auto bg-white rounded-xl shadow-lg overflow-hidden transform transition-all">
      <!-- 头部区域：根据模式切换标题 -->
      <div class="bg-gradient-to-r from-sky-500 to-indigo-600 px-6 py-5">
        <h1 class="text-2xl font-bold text-white flex items-center">
          <font-awesome-icon
              :icon="isAddMode ? 'plus-circle' : 'info-circle'"
              class="mr-2"
          />
          {{ isAddMode ? '新增订单' : '订单详情' }}
        </h1>
        <p v-if="!isAddMode" class="text-sky-100 mt-1">
          订单编号: {{ order.id || 'N/A' }}
        </p>
      </div>

      <!-- 模式切换按钮：仅详情模式显示"新增订单"入口（需外部传递数据） -->
      <div v-if="!isAddMode && !isSubmitted" class="bg-gray-50 px-6 py-3 border-b border-gray-100">
        <button
            :disabled="!hasExternalData"
            class="text-sm text-sky-600 hover:text-sky-800 font-medium flex items-center"
            @click="toggleMode"
        >
          <font-awesome-icon class="mr-1" icon="plus-circle"/>
          新增订单
          <span v-if="!hasExternalData" class="ml-2 text-xs text-gray-500">(需从外部页面传递数据)</span>
        </button>
      </div>

      <!-- 新增订单模式：仅展示外部传递的数据，无手动输入表单 -->
      <div v-if="isAddMode && !isSubmitted" class="p-6 space-y-6">
        <!-- 外部传递数据只读展示（新增前确认） -->
        <div class="bg-blue-50 p-4 rounded-lg border border-blue-100 mb-4">
          <p class="text-blue-700 text-sm font-medium flex items-center">
            <font-awesome-icon class="mr-2" icon="info-circle"/>
            提示：新增订单数据来自外部页面，确认无误后提交
          </p>
        </div>

        <!-- 外部数据展示（完全只读，无输入框） -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">合同模板 <span
                class="text-red-500">*</span></label>
            <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
              {{ externalOrderData.templateName || '未传递' }}
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">合同编号 <span
                class="text-red-500">*</span></label>
            <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
              {{ externalOrderData.contractNo || generateContractNo }}
            </div>
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">订单金额（元）<span
              class="text-red-500">*</span></label>
          <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
            {{ externalOrderData.amount ? Number(externalOrderData.amount).toFixed(2) : '0.00' }}
            <!-- 金额无效提示 -->
            <p v-if="externalOrderData.amount && (isNaN(Number(externalOrderData.amount)) || Number(externalOrderData.amount) <= 0)"
               class="text-red-500 text-xs mt-1">
              金额必须是有效的正数
            </p>
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">购买时间</label>
            <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
              {{ formattedExternalPurchaseTime || '未传递' }}
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">到期时间</label>
            <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
              {{ externalOrderData.expiryDate ? formatDateTime(externalOrderData.expiryDate) : '未设置' }}
            </div>
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">客户ID <span class="text-red-500">*</span></label>
          <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
            {{ externalOrderData.customerId || '未传递' }}
          </div>
        </div>

        <!-- 新增订单操作按钮：仅数据完整时可提交 -->
        <div class="flex justify-end space-x-4 pt-4 border-t border-gray-100">
          <button :disabled="submitLoading"
                  class="px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 transition"
                  type="button"
                  @click="handleCancel">
            取消
          </button>
          <button
              :disabled="submitLoading || !isExternalDataValid"
              class="px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-gradient-to-r from-sky-500 to-indigo-600 hover:from-sky-600 hover:to-indigo-700 transition flex items-center"
              type="button"
              @click="submitNewOrder"
          >
            <span v-if="submitLoading"
                  class="inline-block animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></span>
            确认提交
          </button>
        </div>
      </div>

      <!-- 新增成功提示：提交后显示，强化只读感知 -->
      <div v-if="isSubmitted" class="p-6 text-center bg-green-50 border-b border-green-100">
        <font-awesome-icon class="text-green-500 text-xl mb-2" icon="check-circle"/>
        <p class="text-green-700 font-medium">订单新增成功！数据已锁定，不可编辑</p>
      </div>

      <!-- 支付区域：仅在订单状态为待付款时显示 -->
      <div v-if="isSubmitted && order.statusCode == '1'" class="p-6 bg-white border-b border-gray-200">
        <div class="bg-yellow-50 p-4 rounded-lg border border-yellow-200">
          <h3 class="text-lg font-medium text-yellow-800 mb-2">订单待支付</h3>
          <p class="text-yellow-700 mb-4">您的订单已创建成功，请尽快完成支付以确保服务生效。</p>

          <div class="flex flex-col sm:flex-row sm:items-center sm:space-x-4 space-y-3 sm:space-y-0">
            <div class="text-lg font-semibold text-gray-900">
              支付金额: <span class="text-xl text-green-600">¥{{
                order.amount ? Number(order.amount).toFixed(2) : '0.00'
              }}</span>
            </div>

            <button
                :disabled="payLoading"
                class="px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 transition flex items-center justify-center"
                type="button"
                @click="handlePayment"
            >
              <span v-if="payLoading"
                    class="inline-block animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></span>
              {{ payLoading ? '处理中...' : '立即支付' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 支付成功提示 -->
      <div v-if="paymentSuccess" class="p-6 text-center bg-green-50 border-b border-green-100">
        <font-awesome-icon class="text-green-500 text-xl mb-2" icon="check-circle"/>
        <p class="text-green-700 font-medium">支付成功！订单状态已更新</p>

      </div>

      <!-- 外部数据缺失提示：无数据时显示 -->
      <div v-if="isAddMode && !hasExternalData && !isSubmitted"
           class="p-6 text-center text-yellow-500 bg-yellow-50 border border-yellow-100 rounded-lg">
        <font-awesome-icon class="text-xl mb-2" icon="exclamation-triangle"/>
        <p>未从外部页面获取到订单数据，请先在其他页面完成数据传递</p>

        <!-- 调试信息：仅开发环境显示 -->
        <div v-if="isDevelopment" class="mt-4 text-xs text-left bg-yellow-100 p-3 rounded text-yellow-800">
          <p class="font-medium mb-1">调试信息：</p>
          <p>参数解析错误: {{ paramParseError }}</p>
          <p>检测到的必填字段：</p>
          <ul class="list-disc list-inside space-y-1">
            <li>合同模板：{{ !!externalOrderData.templateName ? '存在' : '缺失' }}</li>
            <li>订单金额：{{ !!externalOrderData.amount && externalOrderData.amount > 0 ? '存在' : '缺失或无效' }}</li>
            <li>客户ID：{{ !!externalOrderData.customerId ? '存在' : '缺失' }}</li>
          </ul>
        </div>

        <button
            class="mt-3 text-sm text-sky-600 hover:underline"
            @click="goBackToSourcePage"
        >
          返回数据来源页面
        </button>
      </div>

      <!-- 订单详情模式：展示完整订单信息 -->
      <div v-else-if="isMounted&&!isAddMode"> <!-- 确保组件已挂载再渲染 -->
        <!-- 数据加载状态 -->
        <div v-if="loading" class="p-10 text-center">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-sky-500 mb-2"></div>
          <p class="text-gray-600">正在加载订单详情...</p>
          <p v-if="isDevelopment" class="text-xs text-gray-500 mt-2">
            查询标识: {{ normalizedQueryId || '未获取' }}
          </p>
        </div>

        <!-- 数据加载失败 -->
        <div v-else-if="loadError" class="p-10 text-center text-red-500">
          <font-awesome-icon class="text-xl mb-2" icon="exclamation-circle"/>
          <p>{{ loadErrorMsg || '获取订单详情失败，请重试' }}</p>
          <p v-if="isDevelopment" class="text-xs mt-2">
            使用查询标识: {{ normalizedQueryId }}
          </p>
          <button
              class="mt-3 text-sm text-sky-500 hover:underline"
              @click="fetchOrderDetail()"
          >
            点击重试
          </button>
        </div>

        <!-- 订单数据为空状态 -->
        <div v-else-if="isEmptyOrder" class="p-10 text-center text-yellow-500">
          <font-awesome-icon class="text-xl mb-2" icon="exclamation-circle"/>
          <p>未找到订单数据</p>
          <p v-if="isDevelopment" class="text-xs mt-2">
            查询标识: {{ order }}
          </p>
          <p v-if="isDevelopment" class="text-xs mt-1">
            API返回的原始数据: {{ JSON.stringify(orderDataRaw) }}
          </p>
          <button
              class="mt-3 text-sm text-sky-500 hover:underline"
              @click="fetchOrderDetail()"
          >
            重新加载
          </button>
        </div>

        <!-- 订单详情展示区域 -->
        <div v-else class="p-6 space-y-6">
          <!-- 订单状态标签 -->
          <div class="flex justify-end">
            <span :class="statusBadgeClass"
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
              <font-awesome-icon :icon="statusIcon" class="mr-1"/>
              {{ statusMap[order.statusCode] || '未知状态' }}
            </span>
          </div>

          <!-- 订单基本信息 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-500 mb-1">合同模板</label>
              <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
                {{ order.templateName || '未设置' }}
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500 mb-1">合同编号</label>
              <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
                {{ order.contractNo || '未设置' }}
              </div>
            </div>
          </div>

          <!-- 金额信息 -->
          <div>
            <label class="block text-sm font-medium text-gray-500 mb-1">订单金额（元）</label>
            <div
                class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-xl font-semibold text-gray-900">
              {{ order.amount ? Number(order.amount).toFixed(2) : '0.00' }}
            </div>
          </div>

          <!-- 时间信息 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-500 mb-1">购买时间</label>
              <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
                {{ order.purchaseTime ? formatDateTime(order.purchaseTime) : '未设置' }}
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500 mb-1">到期时间</label>
              <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
                {{ order.expiryDate ? formatDateTime(order.expiryDate) : '未设置' }}
              </div>
            </div>
          </div>

          <!-- 客户信息 -->
          <div>
            <label class="block text-sm font-medium text-gray-500 mb-1">客户ID</label>
            <div class="w-full py-2 px-4 border border-gray-200 rounded-md bg-gray-50 text-gray-900">
              {{ order.customerId || '未设置' }}
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-end space-x-4 pt-4 border-t border-gray-100">
            <button
                class="px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 transition"
                type="button"
                @click="handleCancel"
            >
              返回
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getOrderApi, submitOrderApi, getOrderByContractNoApi} from '@/api/orders'

export default {
  name: 'OrderDetail',
  data() {
    return {
      // 模式切换标记：true为新增模式，false为详情模式
      isAddMode: false,
      // 新增提交状态：true=已提交，锁定数据不可编辑
      isSubmitted: false,
      // 组件是否已挂载
      isMounted: false,

      // 订单详情数据
      order: {
        id: '',
        number: '',
        templateName: '',
        contractNo: '',
        amount: '',
        purchaseTime: '',
        expiryDate: '',
        statusCode: 1,
        customerId: ''
      },

      // 保存原始API返回数据用于调试
      orderDataRaw: null,
      // 参数解析错误信息
      paramParseError: '',

      // 外部传递的订单数据（从其他页面获取）
      externalOrderData: {},

      // 状态控制
      loading: false,
      loadError: false,
      loadErrorMsg: '',
      submitLoading: false,

      // 支付相关状态
      payLoading: false,
      paymentSuccess: false,
      paymentError: false,
      paymentErrorMsg: ''
    }
  },

  computed: {
    // 判断是否为开发环境
    isDevelopment() {
      return process.env?.NODE_ENV === 'development'
    },

    // 标准化查询标识
    normalizedQueryId() {
      const {orderId, order, contractNo} = this.$route.query;

      // 优先使用contractNo，然后是orderId，最后是order
      let queryId = contractNo || orderId || order;

      // 处理数字类型的ID
      if (queryId !== undefined) {
        return String(queryId).trim();
      }

      return '';
    },

    // 判断订单数据是否为空
    isEmptyOrder() {
      // 检查订单是否有有效数据
      return !this.order.id &&
          !this.order.customerId;
    },

    // 订单状态映射
    statusMap() {
      return {
        '1': '待付款',
        '2': '已付款',
        '3': '已完成',
        '4': '已取消',
        '5': '已退款'
      }
    },

    // 订单状态对应的徽章样式
    statusBadgeClass() {
      const statusClasses = {
        '1': 'bg-yellow-100 text-yellow-800', // 待付款
        '2': 'bg-green-100 text-green-800',  // 已付款
        '3': 'bg-blue-100 text-blue-800',    // 已完成
        '4': 'bg-gray-100 text-gray-800',    // 已取消
        '5': 'bg-red-100 text-red-800'       // 已退款
      }
      return statusClasses[this.order.statusCode] || 'bg-gray-100 text-gray-800'
    },

    // 订单状态对应的图标
    statusIcon() {
      const statusIcons = {
        '1': 'clock-o',     // 待付款
        '2': 'check-circle', // 已付款
        '3': 'flag-checkered', // 已完成
        '4': 'times-circle', // 已取消
        '5': 'undo'         // 已退款
      }
      return statusIcons[this.order.statusCode] || 'question-circle'
    },

    // 格式化外部传递的购买时间
    formattedExternalPurchaseTime() {
      if (!this.externalOrderData.purchaseTime) return ''
      return this.formatDateTime(this.externalOrderData.purchaseTime)
    },

    // 默认到期时间（30天后）
    defaultExpiryTime() {
      const date = new Date()
      date.setDate(date.getDate() + 30)
      return date.toISOString()
    },

    // 生成默认合同编号（外部未传递时使用）
    generateContractNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      return `CON-${year}${month}${day}-${random}`
    },

    // 判断外部数据是否存在（控制新增按钮是否可用）
    hasExternalData() {
      // 增强的日志输出，帮助调试数据问题
      if (this.isDevelopment) {
        console.log('检测外部数据完整性:', {
          templateName: !!this.externalOrderData.templateName,
          amount: !!this.externalOrderData.amount && this.externalOrderData.amount > 0,
          customerId: !!this.externalOrderData.customerId
        })
      }

      // 严格检查金额必须为有效正数
      const validAmount = this.externalOrderData.amount &&
          !isNaN(Number(this.externalOrderData.amount)) &&
          Number(this.externalOrderData.amount) > 0

      return !!this.externalOrderData.templateName &&
          validAmount &&
          !!this.externalOrderData.customerId
    },

    // 外部数据是否完整（控制提交按钮是否可用）
    isExternalDataValid() {
      const validAmount = this.externalOrderData.amount &&
          !isNaN(Number(this.externalOrderData.amount)) &&
          Number(this.externalOrderData.amount) > 0

      return !!this.externalOrderData.templateName &&
          (!!this.externalOrderData.contractNo || !!this.generateContractNo) &&
          validAmount &&
          !!this.externalOrderData.customerId
    }
  },

  created() {
    // 优先从路由query或sessionStorage获取外部传递的数据
    this.getExternalOrderData()
  },

  mounted() {
    // 组件完全挂载后再初始化页面模式和加载数据
    this.isMounted = true;
    this.initPageMode();
  },

  methods: {
    /**
     * 初始化页面模式
     */
    initPageMode() {
      const {mode} = this.$route.query;

      // 调试信息
      if (this.isDevelopment) {
        console.log('初始化页面模式:', {
          mode,
          queryId: this.normalizedQueryId,
          route: this.$route
        });
      }

      // 优先级：mode=add > 订单标识
      if (mode === 'add') {
        this.isAddMode = true;
        // 新增模式下再次尝试获取数据，确保最新
        setTimeout(() => this.getExternalOrderData(), 100);
      }
      // 如果有有效的查询标识，进入详情模式
      else if (this.normalizedQueryId) {
        this.isAddMode = false;
        // 使用$nextTick确保DOM更新后再加载数据
        this.$nextTick(() => {
          this.fetchOrderDetail();
        });
      }
      // 默认进入详情模式（无有效标识则报错）
      else {
        this.isAddMode = false;
        if (this.isMounted) {
          this.loadError = true;
          this.loadErrorMsg = '未获取到有效的订单标识，无法加载详情';
        }
      }
    },

    /**
     * 从外部获取订单数据
     */
    getExternalOrderData() {
      const queryData = this.$route.query
      this.paramParseError = ''; // 重置解析错误

      // 调试日志
      if (this.isDevelopment) {
        console.log('尝试获取外部数据:', {
          queryData,
          sessionStorageData: sessionStorage.getItem('externalOrderData')
        })
      }

      // 优先解析路由中的order参数（序列化的完整订单数据）
      if (queryData.order) {
        try {
          // 尝试JSON解析
          const parsedOrder = JSON.parse(queryData.order);

          // 如果是完整订单对象，作为外部数据处理
          if (typeof parsedOrder === 'object' && parsedOrder !== null) {
            this.externalOrderData = parsedOrder;
            if (this.isDevelopment) {
              console.log('从路由order参数获取完整订单对象:', this.externalOrderData)
            }
            return;
          }

          // 如果是简单值，可能是订单ID
          this.paramParseError = 'order参数是简单值，可能是订单ID而非完整数据';
          console.warn(this.paramParseError);

        } catch (error) {
          // 如果JSON解析失败，记录错误
          this.paramParseError = `order参数解析失败: ${error.message}`;
          console.error(this.paramParseError);
        }
      }

      // 从路由query获取分散的字段
      if (Object.keys(queryData).length > 0) {
        this.externalOrderData = {
          templateName: queryData.templateName || '',
          contractNo: queryData.contractNo || '',
          // 确保金额为数字类型
          amount: queryData.amount !== undefined ? Number(queryData.amount) : 0,
          purchaseTime: queryData.purchaseTime || '',
          expiryDate: queryData.expiryDate || '',
          customerId: queryData.customerId || ''
        }
        if (this.isDevelopment) {
          console.log('从路由参数获取数据:', this.externalOrderData)
        }
        return;
      }

      // 从sessionStorage获取
      const sessionData = sessionStorage.getItem('externalOrderData')
      if (sessionData) {
        try {
          this.externalOrderData = JSON.parse(sessionData)
          // 转换金额为数字类型
          if (this.externalOrderData.amount) {
            this.externalOrderData.amount = Number(this.externalOrderData.amount)
          }
          if (this.isDevelopment) {
            console.log('从sessionStorage获取数据:', this.externalOrderData)
          }
        } catch (error) {
          console.error('解析sessionStorage订单数据失败:', error)
          sessionStorage.removeItem('externalOrderData')
        }
      }

      // 检查是否有数据但未通过验证
      if (Object.keys(this.externalOrderData).length > 0 && !this.hasExternalData) {
        console.warn('检测到外部数据但不完整:', this.externalOrderData)
      }
    },

    // 切换模式：详情→新增（需外部数据存在）
    toggleMode() {
      if (this.isSubmitted) return;

      this.isAddMode = !this.isAddMode;
      if (this.isAddMode) {
        this.getExternalOrderData();
      } else if (this.normalizedQueryId) {
        this.$nextTick(() => {
          this.fetchOrderDetail();
        });
      }
    },

    /**
     * 格式化日期时间
     * @param {String} dateString - 日期时间字符串
     * @returns {String} 格式化后的日期时间
     */
    formatDateTime(dateString) {
      if (!dateString) return ''
      const timeStr = dateString.replace('T', ' ').split('.')[0]
      return timeStr.slice(0, 16)
    },

    // 获取订单详情
    async fetchOrderDetail() {
      if (!this.isMounted) {
        return;
      }

      // 使用标准化的查询标识
      const queryId = this.normalizedQueryId;

      // 验证查询标识有效性
      if (!queryId) {
        this.loading = false;
        this.loadError = true;
        this.loadErrorMsg = '未获取到有效的订单标识，请从正确页面进入';
        return;
      }

      this.loading = true;
      this.loadError = false;
      this.loadErrorMsg = '';
      this.orderDataRaw = null; // 重置原始数据

      try {
        // 增加调试日志
        if (this.isDevelopment) {
          console.log(`正在请求订单详情，查询标识: ${queryId}（类型: ${typeof queryId}）`);
        }

        // 根据不同的标识类型使用不同的查询方式
        let response;
        const {contractNo} = this.$route.query;
        if (contractNo) {
          // 如果有合同编号，使用合同编号查询
          response = await getOrderByContractNoApi(contractNo);
        } else {
          // 否则使用默认的订单ID查询
          response = await getOrderApi(queryId);
        }

        // 保存原始响应数据用于调试
        this.orderDataRaw = response.data || {};

        if (this.isDevelopment) {
          console.log('订单详情API返回数据:', this.orderDataRaw);
        }

        // 检查API返回是否包含有效数据
        if (!this.orderDataRaw || Object.keys(this.orderDataRaw).length === 0) {
          throw new Error('API返回空数据');
        }

        await this.$nextTick(() => {
          this.order = {
            id: this.orderDataRaw.id || 'N/A', // 处理id为null的情况
            number: this.orderDataRaw.number || 'N/A', // 处理number为null的情况
            templateName: this.orderDataRaw.contractName || this.orderDataRaw.templateName || '',
            contractNo: this.orderDataRaw.contractNo || '',
            amount: this.orderDataRaw.payAmount || this.orderDataRaw.amount || 0,
            purchaseTime: this.orderDataRaw.createTime || this.orderDataRaw.purchaseTime || '',
            expiryDate: this.orderDataRaw.expiryDate || '',
            statusCode: typeof this.orderDataRaw.status === 'number' ? this.orderDataRaw.status : 1,
            customerId: this.orderDataRaw.customerId || this.orderDataRaw.custId || ''
          };
        });

      } catch (error) {
        this.loadError = true;
        this.loadErrorMsg = error.response?.data?.message ||
            error.message ||
            '服务器异常，获取订单详情失败';
        console.error('获取订单详情失败：', error);

      } finally {
        this.loading = false;
      }
    },

    // 提交新增订单：使用外部传递的数据
    async submitNewOrder() {
      // 1. 再次验证金额有效性（双重保险）
      const payAmount = Number(this.externalOrderData.amount);
      if (isNaN(payAmount) || payAmount <= 0) {
        this.$message?.error('订单金额必须是有效的正数');
        return;
      }

      // 2. 组装提交数据
      const submitData = {
        contractNo: this.externalOrderData.contractNo || this.generateContractNo,
        contractName: this.externalOrderData.templateName,
        customerId: this.externalOrderData.customerId,
        payAmount: payAmount,
        purchaseTime: this.externalOrderData.purchaseTime || new Date().toISOString(),
        expiryDate: this.externalOrderData.expiryDate || this.defaultExpiryTime
      };

      if (this.isDevelopment) {
        console.log('提交订单数据:', submitData);
      }

      this.submitLoading = true;
      try {
        const response = await submitOrderApi(submitData);

        // 处理API返回结果，即使id为null也继续处理
        if (!response || response.code !== 200) {
          throw new Error(`API返回错误: ${response?.msg || '未知错误'}`);
        }

        const resultData = response.data || {};
        this.$message?.success('订单新增成功！');

        await this.$nextTick(() => {
          this.isSubmitted = true;
          this.isAddMode = false;

          // 直接使用返回的数据更新订单信息，无需再次请求API
          this.order = {
            id: resultData.id || 'N/A', // 处理id为null的情况
            number: resultData.number || 'N/A', // 处理number为null的情况
            templateName: resultData.contractName || '',
            contractNo: resultData.contractNo || '',
            amount: resultData.payAmount || 0,
            purchaseTime: resultData.createTime || '',
            expiryDate: this.externalOrderData.expiryDate || this.defaultExpiryTime,
            statusCode: resultData.status || 1,
            customerId: resultData.customerId || ''
          };

          // 更新URL参数，使用contractNo作为备选标识
          this.$router.replace({
            query: {
              contractNo: resultData.contractNo,
              orderId: resultData.id
            }
          });
        });

      } catch (error) {
        this.$message?.error('创建订单失败：' + (error.response?.data?.message || error.message));
        console.error('创建订单失败：', error);
      } finally {
        this.submitLoading = false;
      }
    },

    /**
     * 处理支付逻辑
     */
    /**
     * 处理支付逻辑
     */
    async handlePayment() {
      // 修复：使用 this.order 替代 this.currentOrder
      if (!this.order.id || this.order.id === 'N/A') {
        this.$message?.error('订单信息错误，无法支付');
        return;
      }

      this.payLoading = true;
      this.paymentError = false;
      this.paymentErrorMsg = '';

      const payParams = {
        userId: Number(this.order.customerId),
        amount: parseFloat(this.order.amount),
        orderId: this.order.id,
        subject: `购买-${this.order.templateName || '订单'}`
      };

      try {
        // 使用 fetch 发起支付请求
        const response = await fetch('http://localhost:8088/api/pay/zfb', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(payParams)
        });

        if (!response.ok) {
          throw new Error(`HTTP错误: ${response.status}`);
        }

        const result = await response.json();

        if (result.code === 200) {
          this.$message?.success('跳转支付宝支付中...');

          if (!result.data || typeof result.data !== 'string') {
            throw new Error('后端返回的表单数据格式不正确');
          }

          // 处理支付宝表单提交
          this.handleAlipay(result.data);
        } else {
          throw new Error(`生成支付表单失败：${result.message || '未知错误'}`);
        }
      } catch (error) {
        this.paymentError = true;
        this.paymentErrorMsg = error.message;

        let errorMsg = '支付请求失败: ';
        if (error.message.includes('Failed to fetch')) {
          errorMsg += '网络连接失败，请检查网络设置';
        } else {
          errorMsg += error.message;
        }

        this.$message?.error(errorMsg);
        console.error('支付请求失败详情:', error);
      } finally {
        this.payLoading = false;
      }
    },

// 添加处理支付宝表单提交的方法
    handleAlipay(formData) {
      // 创建临时表单并提交
      const form = document.createElement('div');
      form.innerHTML = formData;
      document.body.appendChild(form);
      const submitForm = form.querySelector('form');
      if (submitForm) {
        submitForm.submit();
      } else {
        this.$message?.error('支付表单格式错误');
      }
    },


    // 返回数据来源页面
    goBackToSourcePage() {
      this.$router.go(-1);
    },

    // 返回上一页
    handleCancel() {
      this.$router.go(-1);
    }
  }
}
</script>

<style scoped>
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
